package com.linjiang.service;

import com.linjiang.spring.BeanPostProcessor;
import com.linjiang.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * bean的后置处理器实现
 */
@Component
public class LinJiangBeanPostProcessor implements BeanPostProcessor {

    /**
     * bean初始化前调用该方法
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println(beanName+"==>bean初始化前调用postProcessBeforeInitialization");
        if (beanName.equals("service")){
            //给这个bean 设置名字
            ((MyService) bean).setName("xxxService");
        }
        return bean;
    }

    /**
     * bean初始化后调用该方法
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println(beanName+"==>bean初始化后调用postProcessAfterInitialization");
        if (beanName.equals("userService")){
            //生成userService的一个代理对象，通过jdk的方式生成动态代理对象
            Object proxyInstance = Proxy.newProxyInstance(LinJiangBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {

                //代理逻辑
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().equals("doSomeThing")){
                        System.out.println("先执行代理逻辑");
                    }
                    //后调用被代理对象的目标方法
                    return method.invoke(bean, args);
                }
            });
            //返回代理对象
            return proxyInstance;
        }
        return bean;
    }
}
